package com.anyi.shiro;

import com.anyi.entity.SysUser;
import com.anyi.service.SysUserService;
import com.anyi.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 安逸i
 * @version 1.0
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    SysUserService sysUserService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        String  principal = (String)jwtToken.getPrincipal();
        String userId = jwtUtils.getClaimByToken(principal).getSubject();
        SysUser sysUser = sysUserService.getById(userId);
        if(sysUser == null){
            throw new UnknownAccountException("账户不存在");
        }
        if ((sysUser.getStatus()).equals("-1")){
            throw new LockedAccountException("账户已被锁定");
        }
        AccountProfile accountProfile = new AccountProfile();
        BeanUtils.copyProperties(sysUser,accountProfile);
        return new SimpleAuthenticationInfo(accountProfile,jwtToken.getCredentials(),getName());
    }
}
